import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:get/get.dart';

class PushNotificationService {
  static final PushNotificationService _instance = PushNotificationService._();
  factory PushNotificationService() => _instance;
  PushNotificationService._();

  static const _channel = MethodChannel('com.yn_goods.push_notification');
  String? _token;
  
  /// 获取推送 token
  Future<String?> getPushToken() async {
    if (!Platform.isIOS) return null;
    
    try {
      if (_token != null) return _token;
      
      _token = await _channel.invokeMethod<String>('getToken');
      clog('iOS Push Token: $_token', tag: 'PushNotification');
      return _token;
    } on PlatformException catch (e) {
      clog('获取推送 token 失败: ${e.message}', tag: 'PushNotification');
      return null;
    }
  }
  
  /// 检查并请求推送权限
  Future<bool> checkAndRequestNotificationPermission() async {
    if (!Platform.isIOS) return false;
    
    try {
      final bool granted = await _channel.invokeMethod<bool>('requestPermission') ?? false;
      return granted;
    } on PlatformException catch (e) {
      clog('请求推送权限失败: ${e.message}', tag: 'PushNotification');
      return false;
    }
  }
  
  /// 向用户展示权限说明，并请求权限
  Future<bool> showPermissionRequestDialog() async {
    if (!Platform.isIOS) return false;
    
    final bool? result = await Get.dialog<bool>(
      AlertDialog(
        title: Text(LocaleKeys.notification_permission.tr),
        content: Text(LocaleKeys.notification_permission_message.tr),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: Text(LocaleKeys.cancel.tr),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: Text(LocaleKeys.enable_notification.tr),
          ),
        ],
      ),
    );
    
    if (result == true) {
      return await checkAndRequestNotificationPermission();
    }
    
    return false;
  }
} 